<template>
  <!-- 列表 -->
  <ContentWrap>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="paginatedList"
        :stripe="true"
        :show-overflow-tooltip="true"
      >
        <el-table-column
          label="客户"
          align="center"
          prop="nickname"
          width="120"
        />
        <!-- 验收评估部分 -->
        <el-table-column
          label="功能完整性"
          align="center"
          prop="functionality"
          width="120"
        >
          <template #default="{ row }">
            {{ row.functionality === "pass" ? "通过" : "未通过" }}
          </template>
        </el-table-column>
        <el-table-column
          label="性能稳定性"
          align="center"
          prop="performance"
          width="120"
        >
          <template #default="{ row }">
            {{ row.performance === "pass" ? "通过" : "未通过" }}
          </template>
        </el-table-column>
        <el-table-column
          label="使用体验"
          align="center"
          prop="experience"
          width="120"
        >
          <template #default="{ row }">
            {{ row.experience === "pass" ? "通过" : "未通过" }}
          </template>
        </el-table-column>
        <el-table-column
          label="安全性"
          align="center"
          prop="security"
          width="120"
        >
          <template #default="{ row }">
            {{ row.security === "pass" ? "通过" : "未通过" }}
          </template>
        </el-table-column>
        <el-table-column
          label="文档完整性"
          align="center"
          prop="documentation"
          width="120"
        >
          <template #default="{ row }">
            {{ row.documentation === "pass" ? "通过" : "未通过" }}
          </template>
        </el-table-column>
        <el-table-column
          label="未通过说明"
          align="center"
          prop="failureReason"
          width="200"
          show-overflow-tooltip
        />

        <!-- 满意度部分 -->
        <el-table-column
          label="功能实用性"
          align="center"
          prop="functionUsefulness"
          width="120"
        />
        <el-table-column
          label="耐用性"
          align="center"
          prop="durability"
          width="120"
        />
        <el-table-column
          label="售前服务"
          align="center"
          prop="preSales"
          width="120"
        />
        <el-table-column
          label="售后服务"
          align="center"
          prop="afterSales"
          width="120"
        />
        <el-table-column
          label="性价比"
          align="center"
          prop="valueForMoney"
          width="120"
        />
        <el-table-column
          label="重复购买"
          align="center"
          prop="repurchase"
          width="120"
        />

        <!-- 补充调查部分 -->
        <el-table-column
          label="总体满意度"
          align="center"
          prop="overallSatisfaction"
          width="120"
        />
        <el-table-column
          label="是否再次使用"
          align="center"
          prop="reuse"
          width="120"
        >
          <template #default="{ row }">
            {{ row.reuse === "yes" ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          label="改进建议"
          align="center"
          prop="suggestions"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="其他建议"
          align="center"
          prop="comments"
          width="200"
          show-overflow-tooltip
        />

        <el-table-column
          label="时间戳"
          align="center"
          prop="timestamp"
          width="180"
        />
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <Pagination
      :total="filteredTotal"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useUserStoreWithOut } from "@/store/modules/user";
const userStore = useUserStoreWithOut(); // 用户信息缓存
defineOptions({ name: "advise" });

const message = useMessage();

// 定义存储键名
const STORAGE_KEY = "SURVEY_RESULTS";

// 列表相关状态
const loading = ref(true);
const rawDataList = ref<any[]>([]); // 存储原始数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
});

// 展平数据
const surveyList = computed(() => {
  return rawDataList.value.map((item) => {
    const suggestions =
      item.supplement?.suggestions
        ?.map((s: string) => {
          const map: Record<string, string> = {
            ui: "界面优化",
            speed: "提高速度",
            feature: "增加功能",
            price: "价格调整",
            service: "服务改进",
          };
          return map[s] || s;
        })
        .join(", ") || "";

    return {
      // ✅ 添加 nickname
      nickname: item.nickname || "未知用户",

      // 验收评估部分
      ...item.acceptance,

      // 满意度部分
      ...item.satisfaction,

      // 补充调查部分
      overallSatisfaction: item.supplement?.overallSatisfaction,
      reuse: item.supplement?.reuse,
      suggestions,
      comments: item.supplement?.comments,

      timestamp: item.timestamp,
    };
  });
});

// 初始化本地数据
const initLocalData = () => {
  try {
    const allSurveyData: any[] = [];

    // 遍历 localStorage 中的所有键
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.startsWith("SURVEY_RESULTS_")) {
        const raw = localStorage.getItem(key);
        if (raw) {
          const parsed = JSON.parse(raw);
          if (Array.isArray(parsed)) {
            allSurveyData.push(...parsed);
          }
        }
      }
    }

    rawDataList.value = allSurveyData;

    if (allSurveyData.length === 0) {
      message.warning("没有调查数据");
    }
  } catch (e) {
    console.error("加载调查数据失败:", e);
    message.error("加载调查数据失败，请检查数据格式");
    rawDataList.value = [];
  }
};
// 计算属性
const filteredList = computed(() => {
  return [...surveyList.value];
});

const paginatedList = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize;
  const end = start + queryParams.pageSize;
  return filteredList.value.slice(start, end);
});

const filteredTotal = computed(() => filteredList.value.length);

// 方法
const getList = () => {
  loading.value = false;
};

const handleDelete = async (index: number) => {
  try {
    await message.delConfirm("确定删除该调查记录吗？");

    // 计算实际索引
    const actualIndex = (queryParams.pageNo - 1) * queryParams.pageSize + index;

    // 删除原始数据中的对应项
    rawDataList.value.splice(actualIndex, 1);

    // 更新本地存储
    localStorage.setItem(STORAGE_KEY, JSON.stringify(rawDataList.value));
    localStorage.setItem("SURVEY_RESULTS_1", JSON.stringify(rawDataList.value));
    localStorage.setItem(
      "SURVEY_RESULTS_140",
      JSON.stringify(rawDataList.value)
    );
    localStorage.setItem(
      "SURVEY_RESULTS_141",
      JSON.stringify(rawDataList.value)
    );
    // 如果删除的是当前页的最后一条且不是第一页，则跳转到上一页
    if (paginatedList.value.length === 1 && queryParams.pageNo > 1) {
      queryParams.pageNo--;
    }

    message.success("删除记录成功");
  } catch {
    // 用户取消删除
  }
};

// 初始化
onMounted(() => {
  initLocalData();
  getList();
  console.log(paginatedList.value, "paginatedList");
});
</script>

<style scoped>
.table-container {
  width: 100%;
  overflow-x: auto;
}
</style>
